<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/1/18
 * Time: 14:03
 */

namespace app\controller\index;
use app\model\Config;
use app\model\index\Keyword AS model;
use app\model\index\Setmenu;
use app\model\index\UserSearchKeyword;
use app\service\Keyword AS service;
use app\model\index\Order AS order;
use app\model\index\OrderInfo AS info;
use think\facade\Cache;

class Keyword extends Base
{
    public function info()
    {
        try {
            $keywords = input('keyword');
            $type = input('area_type');
            $service = new service();
            if (empty($keywords))
                return $this->fail('没有数据');
            $list = [];
            $keywords = str_replace('，',',',$keywords);
            $array = explode(',',$keywords);
            foreach ($array AS $key => $keyword) {
                if (empty($keyword))continue;
                if ($keyword == $keywords && count($array) > 1)continue;
                $find = UserSearchKeyword::where([
                    'username' => $this->user->username,
                    'keyword' => $keyword,
                    'area_type' => $type
                ])
                    ->find();
                if (empty($find->count)){
                    UserSearchKeyword::create([
                        'username' => $this->user->username,
                        'keyword' => $keyword,
                        'count' => 1,
                        'area_type' => $type,
                        'user_id' => $this->user->id
                    ]);
                }else{
                    $find->count = $find->count + 1;
                    $find->save();
                }
                $field = ['keyword', 'keywords', 'pc', 'phone', 'all','zz_pc', 'zz_phone', 'zz_all', 'price', 'pc_price', 'phone_price','baiduyingxiao_click','baiduyingxiao_type','baiduyingxiao_guiding_price','baiduyingxiao_showreasons','zz_price','baiduyingxiao_price','baiduyingxiao_all'];
                $info = model::field($field)
                    ->where('keyword', $keyword)
                    ->where('update_time', '>', date('Y-m-d', time() - 10 * 86400))
                    ->find();
                if (empty($info->keyword)) {
                    $service->save($keyword);
                    $info = model::field($field)->where('keyword', $keyword)->find();
                }
                $count = info::where('keyword',$keyword)->count();
                $info->total_order = $count;
                $list[] = $info;
//                if ($type == 1) {
//                    $array = Cache::get('keywords_list');
//                    !empty(Cache::has('keywords_list')) && $array = json_decode($array, true);
//                    if (empty($array)) {
//                        $array[] = $info;
//                    } else {
//                        $kws = array_column($array, 'keyword');
//                        if (!in_array($kws, $info->keywords)) {
//                            $temp = array_column($array, null, 'keyword');
//                            $array = [];
//                            foreach ($temp AS $index => $value)
//                                $array[] = $value;
//                            $array[] = $info;
//                        }
//                    }
//                    Cache::set('keywords_list', json_encode($array, JSON_UNESCAPED_UNICODE));
//                }
            }
        }catch (\Exception $e){
            dd($e->getTraceAsString());
        }
        return $this->msg($list);
    }

    public function setmenu()
    {
        $id = input('id');
        $did = input('did');
        $post = input('post.');
        if (!empty($did)){
            Setmenu::where('id',$did)->delete();
            return $this->msg();
        }
        if (empty($post)) {
            if (!empty($id))
                return $this->msg(Setmenu::find($id));
            $list = Setmenu::order('id ASC')
                ->paginate([
                    'page' => $this->page,
                    'list_rows' => $this->size
                ]);
            $rule = json_decode($this->user->rule, true);
            empty($rule) && $rule = [];
            $is_bool = 0;
            if (in_array('setmenu', $rule)) $is_bool = 1;
            return $this->view('/index/keyword/setmenu', ['list' => $list, 'is_bool' => $is_bool]);
        }else {
            if (!empty($id)) {
                Setmenu::where('id',$id)
                    ->save($post);
                return $this->msg();
            } else {
                Setmenu::create($post);
                return $this->msg();
            }
        }
    }

    public function keywords_list(){
        $temp = $array = $message = [];
        !empty(Cache::has('keywords_list')) && $array = json_decode(Cache::get('keywords_list'));
        foreach ($array AS $key => $value){
            if(empty($message[$value->keyword]))
                $message[$value->keyword] = $value;
        }
        foreach ($message AS $key => $value){
            if (count($temp) > 2)break;
            $temp[] = $value;
        }
        return $this->msg($temp);
    }

    public function total_price(){
        $type = input('type');
        $keywords = input('keywords');
        if (empty($keywords)) return $this->fail();
        $keywords = json_decode($keywords);
        switch ($type){
            case 1:$field = 'price';break;
            case 2:$field = 'pc_price';break;
            case 3:$field = 'phone_price';
        }
        $keyword = array_column($keywords,'keyword');
        $price_type = array_column($keywords,'type','keyword');
        $keyword = model::field($field.',keyword')
            ->where('keyword','IN',$keyword)
            ->select();
        $total_price = 0;
        foreach ($keyword AS $key => $value){
            $type = $price_type[$value['keyword']];
            $price = $type == 1 ? $value[$field] : bcmul($value[$field] , 1.5,2);
            $total_price = bcadd($total_price,$price,2);
        }
        return $this->msg([
            'keywords' => $total_price,
        ]);
    }

    public function get_price(){
        $amount = 0;
        $con = input('con');
        $keywords = input('keywords',[]);
        $type = input('type');
        $keyword_area = input('keyword_area');
        $price_ratio = input('con.price_ratio');
        $con['area'] = $con['area'] ?? [];
        foreach ($keywords AS $key => $value){
            if ($keyword_area == 'google') {
                $money = [];
                $array = [
                    '北美区' => [2 => 6000,3 => 4000,4 => 2000],
                    '南美区' => [2 => 4000,3 => 2000,4 => 1000],
                    '西欧区' => [2 => 6000,3 => 4000,4 => 2000],
                    '东欧区' => [2 => 5000,3 => 3000,4 => 2000],
                    '东亚区' => [2 => 5000,3 => 3000,4 => 2000],
                    '东南亚区' => [2 => 4000,3 => 2000,4 => 1000],
                    '南亚区' => [2 => 4000,3 => 2000,4 => 1000],
                    '西亚区' => [2 => 5000,3 => 3000,4 => 2000],
                    '中亚区' => [2 => 3000,3 => 1500,4 => 500],
                    '北非区' => [2 => 3000,3 => 1500,4 => 500],
                    '东非区' => [2 => 3000,3 => 1500,4 => 500],
                    '西非区' => [2 => 4000,3 => 2000,4 => 1000],
                    '中非区' => [2 => 3000,3 => 1500,4 => 500],
                    '南非区' => [2 => 4000,3 => 2000,4 => 1000]
                ];
                $dicount = [10000 => 95, 20000 => 90, 30000 => 85, 40000 => 80, 50000 => 75];
                foreach ($con['area'] AS $index => $item){
                    if(!empty($array[$item])){
                        $count = count(explode(' ',$value['keyword']));
                        switch ($count){
                            case $count <= 2:
                                $count = 2;
                                break;
                            case $count >=4:
                                $count = 4;
                                break;
                            default:
                                $count = 3;
                                break;
                        }
                        $money[] = $array[$item][$count];
                    }
                }
                $ccee = 100;
                $price = floor(array_sum($money));
                foreach ($dicount AS $index => $item){
                    if ($price >= $index) $ccee = $item;
                }
                $price = floor(ceil(3*$ccee * $price_ratio * $price /100)/100)*100;
            }else{
                if ($keyword_area == 'baidu') {
                    $price = $value[$type];
                    if ($con['price_type'] == 'ocpc')
                        $price = $price * Config::get_value('ocpc');
                } else if ($keyword_area == 'douying') {
                    $price = $value['price'];
                    $price = $price * Config::get_value('douyin');
                } else if ($keyword_area == 'all') {
                    $temp = $value['price'];
                    $price = $value[$type];
                    if ($con['price_type'] == 'ocpc')
                        $price = $price * Config::get_value('ocpc');
                    $temp = $temp * Config::get_value('douyin');
                    $price = $temp + $price;
                } else {
                    return $this->fail('请选择平台');
                }
                if(count($con['area']) >= 1 && count($con['area']) < 3){
                    $price = $price * 0.4 ;
                }elseif(count($con['area']) >= 3 && count($con['area']) < 5){
                    $price = $price * 0.5 ;
                }elseif(count($con['area']) >= 5 && count($con['area']) < 7){
                    $price = $price * 0.7 ;
                }elseif(count($con['area']) >= 7 && count($con['area']) < 9) {
                    $price = $price  *  0.8 ;
                }elseif(count($con['area']) >= 10 && count($con['area']) < 12) {
                    $price = $price  *  0.9 ;
                }elseif(count($con['area']) >= 12){
                    $price = $price * 1;
                }else{
                    $price = 0;
                }
            }
            if($con['word_day'] == '半年')
                $price = $price * 0.6 ;
            if($con['word_hover'] == '24小时')
                $price = $price * Config::get_value('price_24');
            $price = floor(ceil($price/100)*100);
            $keywords[$key]['price'] = $price;
            $amount = $amount + $price;
        }
        $key = md5(uniqid().rand(100,999));
        Cache::set($key,['amount' => $amount,'keywords' => $keywords],600);
        return $this->msg([
            'amount' => $amount,
            'keywords' => $keywords,
            'uniqid' => $key
        ]);
    }

    public function order_save(){
        $post = input('post.');
        switch ($post['type']){
            case 'price';$type = 1;break;
            case 'pc_price';$type = 2;break;
            case 'phone_price';$type = 3;break;
        }
        $data = Cache::get($post['key']);
        $order_no = date('YmdHis').rand(10000,99999);
        $keywords = $data['keywords'];
        $count['baidu'] = info::where('keyword','IN',array_column($keywords,'keyword'))
            ->where('status',2)
            ->where('end_date','>',date('Y-m-d'))
            ->where('keyword_area', 'baidu')
            ->count();
        $count['douying'] = info::where('keyword','IN',array_column($keywords,'keyword'))
            ->where('status',2)
            ->where('end_date','>',date('Y-m-d'))
            ->where('keyword_area', 'douying')
            ->count();
        $count['google'] = info::where('keyword','IN',array_column($keywords,'keyword'))
            ->where('status',2)
            ->where('end_date','>',date('Y-m-d'))
            ->where('keyword_area', 'google')
            ->count();
        if ($post['keyword_area'] == 'all') {
            if ($count['baidu'] > 1)
                return $this->fail('该关键词百度平台已经无法下单');
            if ($count['douying'] > 1)
                return $this->fail('该关键词抖音平台已经无法下单');
        }else if($post['keyword_area'] == 'baidu') {
            if ($count['baidu'] > 1)
                return $this->fail('该关键词百度平台已经无法下单');
        }else if($post['keyword_area'] == 'douying') {
            if ($count['douying'] > 1)
                return $this->fail('该关键词抖音平台已经无法下单');
        }else if ($post['keyword_area'] == 'google'){
            if ($count['google'] > 1)
                return $this->fail('该关键词谷歌平台已经无法下单');
        }else{
            return $this->fail('平台未选择');
        }
        if ($this->user->pid > 0)
            $user_id = $this->user->pid;
        else
            $user_id = $this->user->id;
        $discount = \app\model\index\User::where('id',$user_id)->value('discount');
        $order = order::create([
            'order_no' => $order_no,
            'address' => implode(',',$post['con']['area']),
            'user_id' => $user_id,
            'amount' => ceil($data['amount'] * $discount),
            'type' => $type,
            'keyword_area' => $post['keyword_area'],
            'word_hover' => $post['con']['word_hover'] ?? '',
            'word_day' => $post['con']['word_day'] ?? '',
            'price_type' => $post['con']['price_type'] == 'ocpc' ? 2 : 1,
            'word_type' => !empty($post['con']['word_type']) ? implode(',',$post['con']['word_type']) : '',
        ]);
        foreach ($keywords AS $key => $value){
            $info[] = [
                'order_no' => $order_no,
                'user_id' => $user_id,
                'keyword' => $value['keyword'],
                'price' => ceil($value['price'] * $discount),
                'type' =>  $type,
                'price_type' => $post['con']['price_type'] == 'ocpc' ? 2 : 1,
                'keyword_area' => $post['keyword_area'],
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        $order->info()->insertAll($info);
        return $this->msg(order::where('order_no',$order_no)->with(['info'])->find());
    }

    public function order_list(){
        $get = input('get.');
        $post = input('post.');
        if(!empty($get)) $post = $get;
        $where = $parent = [];
        $order_no = input('order_no','');
        !empty($post['order']) && $where[] = ['order_no','like','%'.$post['order'].'%'];
        !empty($post['keyword']) && $where[] = ['keyword','like','%'.$post['keyword'].'%'];
        !empty($post['address']) && $parent[] = ['address','like','%'.$post['address'].'%'];
        !empty($post['word_day']) && $parent[] = ['word_day','like','%'.$post['word_day'].'%'];
        !empty($post['word_hover']) && $parent[] = ['word_hover','like','%'.$post['word_hover'].'%'];
        !empty($post['word_type']) && $parent[] = ['word_type','like','%'.$post['word_type'].'%'];
        !empty($post['keyword_type']) && $where[] = ['type','=',$post['keyword_type']];
        !empty($post['price_type']) && $where[] = ['price_type','=',$post['price_type']];
//        dd($where);
        $list = info::where($where)
            ->with(['order_data']);
        !empty($parent) && $list = $list
            ->where('order_no','IN',function($sql) use ($parent){
                $sql->name('order')->field('order_no')->where($parent)->select();
            });
        $list = $list
            ->where('user_id','=',$this->user->id)
            ->order('create_time DESC')
            ->paginate([
                'page' => $this->page,
                'order' => $post['order'] ?? '',
                'order_no' => $order_no,
                'list_rows' => $this->size
            ]);
        return $this->msg($list);
    }

    public function list(){
        $user_id = $this->user->pid == 0 ? $this->user->id : $this->user->pid;
        $keywords = info::where('user_id',$user_id)
            ->where('status',2)
            ->with(['order_data'])
            ->order('end_date ASC')
            ->paginate(['page' => $this->page,'list_rows' => $this->size]);
        return $this->view('/index/keyword/list',['list' => $keywords]);
    }

    public function google(){
        $keyword = input('keyword');
        $user = \app\model\index\User::where('username',$_SESSION['username'])->find();
        $rule = json_decode($user->rule,true);
        $rule = empty($rule) ? [] : $rule;
        return $this->view('/index/google',[
            'user' => $user,
            'keyword' => $keyword,
            'is_message' => in_array('message',$rule) ? 1 : 0,
            'is_order' => in_array('order',$rule)
        ]);
    }

    public function baidu(){
        $post = input('post.',[]);
        if (!empty($post['keyword'])){
            \think\facade\Db::name('keywords_spotting')->insert($post);
            return $this->msg();
        }
        if (!empty($post['email'])){
            \think\facade\Db::name('keywords_email')->insert($post);
            return $this->msg();
        }
        $idk = input('idk',0);
        if (!empty($idk))
            \think\facade\Db::name('keywords_spotting')->where('id',$idk)->delete();
        $ide = input('ide',0);
        if (!empty($ide))
            \think\facade\Db::name('keywords_email')->where('id',$ide)->delete();
        $list = \think\facade\Db::name('keywords_spotting')->paginate(['page' => $this->page,'list_rows' => $this->size]);
        $users = \think\facade\Db::name('keywords_email')->paginate(['page' => $this->page,'list_rows' => $this->size]);
        return $this->view('/index/spotting/baidu',[
            'list' => $list,
            'user' => $users
        ]);
    }

    public function douyin(){
        return $this->view('/index/spotting/douyin',[

        ]);
    }
}